/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.logistics.web.overseaswarehouse;

import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.entity.warehouse.Twarehouse;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.base.service.warehouse.TwarehouseService;
import com.jeesite.modules.custom.enumInfo.logisticsStatusEnum;
import com.jeesite.modules.custom.enumInfo.warhouseTypeEnum;
import com.jeesite.modules.logistics.entity.ladingbill.LadingBillDetail;
import com.jeesite.modules.logistics.entity.overseaswarehouse.OverseasWarehouse;
import com.jeesite.modules.logistics.entity.overseaswarehouse.OverseasWarehouseDetail;
import com.jeesite.modules.logistics.service.overseaswarehouse.OverseasWarehouseService;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 海外仓Controller
 *
 * @author LV
 * @version 2021-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/logistics/overseaswarehouse/overseasWarehouse")
public class OverseasWarehouseController extends BaseController {

    @Autowired
    private OverseasWarehouseService overseasWarehouseService;
    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private TwarehouseService warehouseService;
    @Autowired
    private TcarService carService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public OverseasWarehouse get(String overseasWarehouseId, boolean isNewRecord) {
        return overseasWarehouseService.get(overseasWarehouseId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:view")
    @RequestMapping(value = {"list", ""})
    public String list(OverseasWarehouse overseasWarehouse, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        Twarehouse warehouse = new Twarehouse();
        warehouse.setOwnership(warhouseTypeEnum.OVERSEAS.getCode());
        model.addAttribute("listWarehouse", warehouseService.findList(warehouse));
        model.addAttribute("overseasWarehouse", overseasWarehouse);
        return "modules/logistics/overseaswarehouse/overseasWarehouseList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page < OverseasWarehouse > listData(OverseasWarehouse overseasWarehouse, HttpServletRequest request, HttpServletResponse response) {
        overseasWarehouse.setPage(new Page <>(request, response));
        Page < OverseasWarehouse > page = overseasWarehouseService.findPage(overseasWarehouse);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:view")
    @RequestMapping(value = "form")
    public String form(OverseasWarehouse overseasWarehouse, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("listWarehouse", warehouseService.findList(new Twarehouse()));
        model.addAttribute("tcarList", carService.findList(new Tcar()));
        for (OverseasWarehouseDetail overseasWarehouseDetail : overseasWarehouse.getOverseasWarehouseDetailList()) {
            overseasWarehouseDetail.setCarName(overseasWarehouseDetail.getTcar().getCarName());
            overseasWarehouseDetail.setFrameNumberOld(overseasWarehouseDetail.getFrameNumber());
        }
        model.addAttribute("overseasWarehouse", overseasWarehouse);
        return "modules/logistics/overseaswarehouse/overseasWarehouseForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:view")
    @RequestMapping(value = "detail")
    public String detail(OverseasWarehouse overseasWarehouse, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("listWarehouse", warehouseService.findList(new Twarehouse()));
        model.addAttribute("tcarList", carService.findList(new Tcar()));
        model.addAttribute("overseasWarehouse", overseasWarehouse);
        return "modules/logistics/overseaswarehouse/overseasWarehouseDetail";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated OverseasWarehouse overseasWarehouse) {
        /**
         * 车间耗校验重复
         * 1、已经删除的行信息的车架号
         * 2、新增或修改的行信息的车架号
         * 3、搜出除除订单行之外的车架号信息--去重后，将新增和删除的车架号信息增加到其中，判断是否重复
         */
        List<String> newFameNumbers = ListUtils.newArrayList();
        List<String> deleteFameNumbers = ListUtils.newArrayList();
        for (OverseasWarehouseDetail overseasWarehouseDetail : overseasWarehouse.getOverseasWarehouseDetailList()) {
            if (!LadingBillDetail.STATUS_DELETE.equals(overseasWarehouseDetail.getStatus())){
                if (StringUtils.isNoneEmpty(overseasWarehouseDetail.getFrameNumber())){
                    newFameNumbers.add(overseasWarehouseDetail.getFrameNumber());
                }
            }else{
                if (StringUtils.isNoneEmpty(overseasWarehouseDetail.getFrameNumber())){
                    deleteFameNumbers.add(overseasWarehouseDetail.getFrameNumber());
                }
            }
        }
        List<String> frameNumberByRemove = serviceOrderService.getFrameNumberByRemove(deleteFameNumbers);
        frameNumberByRemove.addAll(newFameNumbers);
        Integer newFrameNumberCount = frameNumberByRemove.size();
        List<String> list1 = frameNumberByRemove.stream().distinct().collect(Collectors.toList());
        if (newFrameNumberCount != list1.size()){
            return renderResult(Global.FALSE, text("存在相同的车架号！"));
        }


        overseasWarehouseService.save(overseasWarehouse);
        /*try {
        } catch (Exception e) {
            return renderResult(Global.FALSE, text("操作存在异常，请联系管理员！"));
        }*/
        return renderResult(Global.TRUE, text("保存海外仓成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(OverseasWarehouse overseasWarehouse) {
        overseasWarehouseService.delete(overseasWarehouse);
        return renderResult(Global.TRUE, text("删除海外仓成功！"));
    }

    /**
     * 列表选择对话框
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:view")
    @RequestMapping(value = "overseasWarehouseSelect")
    public String empUserSelect(OverseasWarehouse overseasWarehouse, String selectData, Model model) {
        String selectDataJson = EncodeUtils.decodeUrl(selectData);
        if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()) {
            model.addAttribute("selectData", selectDataJson);
        }
        model.addAttribute("OverseasWarehouse", overseasWarehouse);
        return "modules/logistics/overseaswarehouse/overseasWarehouseSelect";
    }

    /**
     * 创建自 服务订单
     */
    @RequiresPermissions("logistics:overseaswarehouse:overseasWarehouse:view")
    @RequestMapping(value = "createFromServiceOrder")
    public String createFromServiceOrder(ServiceOrder serviceOrder, Model model) {
        ServiceOrder oldServiceOrder = serviceOrderService.get(serviceOrder);
        if (oldServiceOrder != null && StringUtils.isNotEmpty(oldServiceOrder.getServiceOrderId())) {
            OverseasWarehouse overseasWarehouse = new OverseasWarehouse();
            // 服务订单
            overseasWarehouse.setServiceOrderId(oldServiceOrder.getServiceOrderId());
            // 客户名称
            overseasWarehouse.setCustomerId(oldServiceOrder.getCustomer().getCustomerId());
            // 外商名称
            overseasWarehouse.setForeignBusinessmenId(oldServiceOrder.getForeignBusinessmenId());
            //国内资方
            overseasWarehouse.setInvestorId(oldServiceOrder.getInvestorId());
            // 供货外商
            overseasWarehouse.setSupplierId(oldServiceOrder.getSupplierId());
            // 子表信息
            List < OverseasWarehouseDetail > overseasWarehouseDetailList = ListUtils.newArrayList();
            List < ServiceOrderDetail > serviceOrderDetailList = oldServiceOrder.getServiceOrderDetailList();
            for (ServiceOrderDetail SODetail : serviceOrderDetailList) {
                if (StringUtils.isEmpty(SODetail.getOverseasWarehouseId())) {
                    OverseasWarehouseDetail warehouseDetail = new OverseasWarehouseDetail();
                    warehouseDetail.setRowNumber(SODetail.getRowNumber());
                    warehouseDetail.setCarId(SODetail.getCarId());
                    warehouseDetail.setCarName(SODetail.getTcar().getCarName());
                    warehouseDetail.setModel(SODetail.getModel());
                    warehouseDetail.setWarehousestatus(logisticsStatusEnum.CAR_TAKE.getCode());
                    overseasWarehouseDetailList.add(warehouseDetail);
                }
            }
            overseasWarehouse.setOverseasWarehouseDetailList(overseasWarehouseDetailList);

            model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
            model.addAttribute("listCustomer", customerService.findList(new Customer()));
            model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
            model.addAttribute("listWarehouse", warehouseService.findList(new Twarehouse()));
            model.addAttribute("tcarList", carService.findList(new Tcar()));
            model.addAttribute("overseasWarehouse", overseasWarehouse);
            return "modules/logistics/overseaswarehouse/overseasWarehouseForm";
        } else {
            return renderResult(Global.FALSE, text("未查找到服务订单的相关信息！"));
        }
    }

}